package bdddaosimpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import bdd.beans.Contratquadriennal;
import bdd.beans.DBLink;
import bdd.beans.Role;
import bdd.beans.Type;
import bdd.beans.Typeposte;
import bdddaos.DAOType;
import bdddaos.DAOType;

public class DAOTypeImpl implements DAOType {

	
	private DBLink dblink;
	
	public DAOTypeImpl() {
		dblink = new DBLink();
	}
	
	@Override
	public Type save(Type o) {		
		try {
			dblink.connexion();
			this.dblink.setPst(this.dblink.getConnection().prepareStatement("INSERT INTO TYPE (libelle)" +
					" VALUES ('"+o.getLibelle()+"')"));
			this.dblink.getPst().executeQuery();
			DAOOutils outil = new DAOOutils();
			o.setNumtype(outil.findMaxId("TYPE", "IDTYPE"));
		}
		catch(SQLException se) {
			System.out.println("Erreur de requ�te");
		}
		finally{
			dblink.deconnexion();
		}
		return o;
	}

	@Override
	public Type find(Integer id) {
		Type o = new Type();
		o.setNumtype(id);
		try {
			this.dblink.connexion();
			String r = "SELECT * FROM TYPE WHERE IDTYPE = " + id;
			this.dblink.setPst(this.dblink.getConnection().prepareStatement(r));
			ResultSet rs = this.dblink.getPst().executeQuery();
			if(rs.next()) {
				o.setLibelle(rs.getString("LIBELLE"));
			}		
		}
		catch(SQLException se) {
			System.out.println("Erreur de requ�te" + se);
		}
		finally{
			this.dblink.deconnexion();
		}
		return o;
	}

	@Override
	public List<Type> findAll() {
		List<Type> Lstretour = new ArrayList<Type>();
		try {
			this.dblink.connexion();
			this.dblink.setPst(this.dblink.getConnection().prepareStatement("SELECT * FROM TYPE"));
			ResultSet rs = this.dblink.getPst().executeQuery();
			while(rs.next()) {
				Type retour = new Type();
				retour.setLibelle(rs.getString("LIBELLE"));
				retour.setNumtype(rs.getInt("NUMTYPE"));
				Lstretour.add(retour);
			}		
		}
		catch(SQLException se) {
			System.out.println("Erreur de requ�te" + se);
		}
		finally{
			this.dblink.deconnexion();
		}
		return Lstretour;
	}

	@Override
	public void update(Type o) {
		try {
			this.dblink.connexion();
			String r = "UPDATE TYPE SET LIBELLE='"+o.getLibelle()+ "' WHERE NUMTYPE="+o.getNumtype();
			
			this.dblink.setPst(this.dblink.getConnection().prepareStatement(r));
			this.dblink.getPst().executeQuery();
		}
		catch(SQLException se) {
			System.out.println("Erreur de requ�te : " + se);
		}
		finally{
			this.dblink.deconnexion();
		}
	}

	@Override
	public void delete(Type o) {
		try {
			dblink.connexion();
			this.dblink.setPst(this.dblink.getConnection().prepareStatement("DELETE FROM TYPE WHERE NUMTYPE = " + o.getNumtype()));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			dblink.deconnexion();
		}
	}

}
